package y2016.test;

import java.io.*;

/**
 * 检测文件类
 */

public class JudgeFile {


    /**
     * 获取文件编码格式
     *
     * @param absolute_path 文件路径，根据文件绝对路径获取输入流，通过读取文件头，判断编码方式
     * @return 编码的字符串，如：UTF-8，Unicode，ANSI，GBK
     */
    public String getEncoding(InputStream in) {
        int p = 0;
        try {
            BufferedInputStream bin = new BufferedInputStream(in);
            p = (bin.read() << 8) + bin.read();
            bin.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String encoding = null;
        switch (p) {
            case 0xefbb:
                encoding = "UTF-8";
                break;
            case 0xfffe:
                encoding = "Unicode";
                break;
            case 0xfeff:
                encoding = "UTF-16BE";
                break;
            case 0x5c75:
                encoding = "ANSI";//ANSI|ASCII
                break;
            default:
                encoding = "GBK";
        }

        return encoding;
    }

    /**
     * 获取文件编码格式
     *
     * @return 编码的字符串，如：UTF-8，Unicode，ANSI，GBK
     */
    public String getEncoding(File file) {
        int p = 0;
        try {
            InputStream in = new FileInputStream(file);
            BufferedInputStream bin = new BufferedInputStream(in);
            p = (bin.read() << 8) + bin.read();
            bin.close();
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String encoding = null;
        switch (p) {
            case 0xefbb:
                encoding = "UTF-8";
                break;
            case 0xfffe:
                encoding = "Unicode";
                break;
            case 0xfeff:
                encoding = "UTF-16BE";
                break;
            case 0x5c75:
                encoding = "ANSI";//ANSI|ASCII
                break;
            default:
                encoding = "GBK";
        }
        //				kCFStringEncodingGB_2312_80 = 0x0630,
        //				kCFStringEncodingGBK_95 = 0x0631,        /* annex to GB 13000-93; for Windows 95 */
        //				kCFStringEncodingGB_18030_2000 = 0x0632,
        return encoding;
    }


}
